package com.ghost.librariandb;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;


public class AddBookPanel extends JPanel
{
	private JTextField txtBookName;
	private JTextField txtAuthor;
	private JTextField txtTags;
	private JButton btnAddBook;

	/**
	 * Create the panel.
	 */
	public AddBookPanel()
	{
		setLayout(null);
		
		JLabel lblBookName = new JLabel("Book Name:");
		lblBookName.setBounds(10, 14, 93, 14);
		add(lblBookName);
		
		txtBookName = new JTextField();
		txtBookName.setColumns(10);
		txtBookName.setBounds(113, 11, 200, 20);
		add(txtBookName);
		
		txtAuthor = new JTextField();
		txtAuthor.setColumns(10);
		txtAuthor.setBounds(113, 36, 200, 20);
		add(txtAuthor);
		
		JLabel lblAuthor = new JLabel("Author:");
		lblAuthor.setBounds(10, 39, 46, 14);
		add(lblAuthor);
		
		JLabel lblTags = new JLabel("Tags:");
		lblTags.setBounds(10, 64, 46, 14);
		add(lblTags);
		
		txtTags = new JTextField();
		txtTags.setBounds(113, 61, 200, 20);
		add(txtTags);
		txtTags.setColumns(10);
		
		btnAddBook = new JButton("Add Book");
		btnAddBook.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent event)
			{
//				System.out.println("I am just clicked");
				Date now = new Date();
				int bookID = 1;
				Connection connection = DataProvider.getConnection();
				Statement statement = null;
				try
				{
					statement = connection.createStatement();
					statement.setQueryTimeout(30);
					ResultSet rs = statement.executeQuery("select ID from Book order by ID DESC");
					while (rs.next())
					{
						bookID = bookID + rs.getInt("ID");
						System.out.println("New Book ID: " + bookID);
						break;
					}
					statement.executeUpdate("insert into Book values(" + Integer.toString(bookID) + ", '" + txtBookName.getText() + "', '" + txtAuthor.getText() + "', '" + txtTags.getText() + "', " + Long.toString(now.getTime()) + ", 0, 0, 0)");
					txtBookName.setText("");
					txtAuthor.setText("");
					txtTags.setText("");
				}
				catch (SQLException e)
				{
					e.printStackTrace();
				}
				finally
				{
					if (statement != null)
					{
						try
						{
							statement.close();
						}
						catch (SQLException e)
						{
							e.printStackTrace();
						}
					}
				}
			}
		});
		btnAddBook.setBounds(113, 105, 89, 23);
		add(btnAddBook);

	}
}
